package educrypt.cryptanalysis.vigenere;

import java.util.ArrayList;
import java.util.List;

import educrypt.commons.Alphabet;
import educrypt.commons.Text;

public class KasiskiExamination {

	public static int examine(Text cipherText, Alphabet alphabet) {
		final double THRESHOLD = 1.6;
		int keyLength = 0;

		Text filteredCipherText = cipherText.removeUnknownSymbols(alphabet);

		List<Integer> prevCoincidences = new ArrayList<Integer>();
		for (int i = 1; i < cipherText.size() && keyLength == 0; i++) {
			int coincidences = 0;
			for (int j = 0; j < filteredCipherText.size(); j++) {
				if (filteredCipherText.getSymbolAt(j) == filteredCipherText
						.getSymbolAt((j + i) % filteredCipherText.size())) {
					coincidences++;
				}
			}
			if (i > 1) {
				double incrementRatio = (double) coincidences
						/ (double) average(prevCoincidences);
				if (incrementRatio >= THRESHOLD) {
					keyLength = i;
				}
			}
			prevCoincidences.add(coincidences);
		}
		return keyLength;
	}

	private static int average(List<Integer> values) {
		int sum = 0;
		for (int value : values) {
			sum += value;
		}
		return sum / values.size();
	}
}
